package com.monkeyboy.tree;

import com.monkeyboy.TreeNode;

import java.util.Arrays;

/**
 * 重建二叉树
 * 根据二叉树的前序遍历和中序遍历的结果，重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
 * <p>
 * 解题思路：
 * 利用递归进行构建二叉树
 *
 * @Author Gavin
 * @date 2021.04.08 09:22
 */
public class Tree01 {

    public TreeNode solution(int[] pre, int[] in) {
        if (pre.length == 0 || in.length == 0) {
            return null;
        }
        TreeNode root = new TreeNode(pre[0]);
        //在中序中找到前序的根
        for (int i = 0; i < in.length; i++) {
            if (in[i] == pre[0]) {
                //递归构建左子树
                //Arrays.copyOfRange 左闭右开
                root.left = solution(Arrays.copyOfRange(pre, 1, i + 1), Arrays.copyOfRange(in, 0, i));
                //右子树
                root.right = solution(Arrays.copyOfRange(pre, i + 1, pre.length), Arrays.copyOfRange(in, i + 1, in.length));
                break;
            }
        }
        return root;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6};
        int[] a = Arrays.copyOfRange(arr, 0, 3);//左闭右开
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
}
